import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';

typedef OnWidgetSizeChange = void Function(Size size);

class HcWidgetUtil {
  const HcWidgetUtil._();

  static Object measureWidgetSize(Widget widget) {
    Size result = const Size(0, 0);
    MeasureSize(
        child: widget,
        onChange: (size) {
          result = size;

        });
    return result;
  }
}

class _MeasureSizeRenderObject extends RenderProxyBox {
  Size? oldSize;
  final OnWidgetSizeChange onChange;

  _MeasureSizeRenderObject(this.onChange);

  @override
  void performLayout() {
    // TODO: implement performLayout
    super.performLayout();
    Size? newSize = child?.size ?? Size.zero;
    if (oldSize != null && oldSize == newSize) {
      return;
    }
    oldSize = newSize;
    WidgetsBinding.instance.addPostFrameCallback((_) => onChange(newSize));
  }
}

class MeasureSize extends SingleChildRenderObjectWidget {
  final OnWidgetSizeChange onChange;

  const MeasureSize({required Widget child, required this.onChange, Key? key})
      : super(key: key, child: child);

  @override
  RenderObject createRenderObject(BuildContext context) {
    print("走进来了吗>");
    // TODO: implement createRenderObject
    return _MeasureSizeRenderObject(onChange);
  }
}
